package org.bjf.config;

import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.google.common.collect.Maps;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

@Configuration
public class DruidMonitorConfig {

    /**
     * 注册ServletRegistrationBean
     */
    @Bean
    public ServletRegistrationBean<StatViewServlet> statViewServlet() {
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");

        Map<String, String> paramMap = Maps.newHashMap();
        //账号密码.
        paramMap.put(StatViewServlet.PARAM_NAME_USERNAME, "root");
        paramMap.put(StatViewServlet.PARAM_NAME_PASSWORD, "root");
        //IP白名单 (没有配置或者为空，则允许所有访问)
        paramMap.put(StatViewServlet.PARAM_NAME_ALLOW, "");
        //IP黑名单 (共存时，deny优先于allow)
        paramMap.put(StatViewServlet.PARAM_NAME_DENY, "192.88.88.88");
        //禁用HTML页面上的“Reset All”功能
        paramMap.put(StatViewServlet.PARAM_NAME_RESET_ENABLE, "false");

        bean.setInitParameters(paramMap);
        return bean;
    }

    /**
     * 注册FilterRegistrationBean
     */
    @Bean
    public FilterRegistrationBean<WebStatFilter> webStatFilter() {
        FilterRegistrationBean<WebStatFilter> bean = new FilterRegistrationBean<>(new WebStatFilter());
        //添加过滤规则.
        bean.addUrlPatterns("/*");
        //过滤排除.
        bean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return bean;
    }

}